<template>
  <div class="c-bg-sgray c-pb40 container">
    <audio id="audio" @ended="playAudioEnd" class="c-pf c-p-l-100"></audio>
    <div :class="homeWorkInfo.name?'c-bg-white c-pb10':''">
      <div class="c-fs20 c-fs30 c-textAlign-c c-ph24 c-lh c-text-ellipsis1"
        :class="(homeWorkInfo.description && homeWorkInfo.description.length > 0) ||
          homeWorkInfo.cover != '' || (homeWorkInfo.description.length == 1||(homeWorkInfo.description[0]&&homeWorkInfo.description[0].content != ''))?'c-pt36':homeWorkInfo.name?'c-pv36':'c-pt36'">
        {{homeWorkInfo.name}}
      </div>
    </div>
    <div class="c-bg-white">
      <div v-if="homeWorkInfo.cover" class="c-text-hidden c-mb10">
        <img class="c-w100" :class="cfg.isCopyPicture == 0 ? 'imgCloseBig' : ''" :src="$addXossFilter(homeWorkInfo.cover)" alt="" />
      </div>

      <clock-course-detail-com :showAudioRecordModal='showAudioRecordModal' class="c-pb30" v-if="homeWorkInfo.description && homeWorkInfo.description.length > 0 && (homeWorkInfo.cover != '' || (homeWorkInfo.description.length == 1 ? homeWorkInfo.description[0].content != '' : true))" :status='0' :description='homeWorkInfo.description' @clickShowDesc='clickShowDesc' @clickShowVideo='clickShowVideo'>
      </clock-course-detail-com>
      <div class="c-ph24 c-pb30" v-if="baseSetting.needWordNum || baseSetting.needAudioNum || baseSetting.needVideoNum || baseSetting.needPictureNum">
        <div class="c-fs20 c-flex-row c-pv20 c-ph24 theme-bg-10 c-br8">
          <div class="c-pr10 c-fc-xblack c-ww160 c-mt6">要求至少上传：</div>
          <div class="c-flex-row c-flexw-wrap c-ww400">
            <div class="c-ph10 theme-fc theme-bd1 c-bg-white c-br8 c-mr10 c-mt6" v-if="baseSetting.needWordNum * 1 > 0">{{baseSetting.needWordNum}}个字</div>
            <div class="c-ph10 theme-fc theme-bd1 c-bg-white c-br8 c-mr10 c-mt6" v-if="baseSetting.needAudioNum * 1 > 0">{{baseSetting.needAudioNum}}秒音频</div>
            <div class="c-ph10 theme-fc theme-bd1 c-bg-white c-br8 c-mr10 c-mt6" v-if="baseSetting.needVideoNum * 1 > 0">{{baseSetting.needVideoNum}}个视频</div>
            <div class="c-ph10 theme-fc theme-bd1 c-bg-white c-br8 c-mr10 c-mt6" v-if="baseSetting.needPictureNum * 1 > 0">{{baseSetting.needPictureNum}}张图片</div>
          </div>
        </div>
      </div>
    </div>
    <div class="c-bg-white c-br20 c-mh24 c-mt20 c-ph24 c-pv24">
      <!-- 文字回答 -->
      <div class="modal-textarea c-bd-b1 c-br20 c-mb30">
        <textarea @focus="inputFocus" @blur="inputBlur" v-model="answerText" maxlength="10000" class="needsclick c-lh40" placeholder="请输入打卡内容"></textarea>
        <div class="c-w100 c-lh c-pt10 c-textAlign-r c-fs18  c-fc-sgray">{{answerText.length}}/10000</div>
      </div>
      <!-- <div class="c-flex-row c-flexw-wrap c-mt20"> -->
      <!-- 语音回答 -->
      <!-- <div  @click="clickPlayAudio(item.url)" class="c-ww100 c-hh48 c-br10 c-bg-xgreen c-ph10 c-flex-row c-justify-sb c-p c-flex-row c-aligni-center c-mb20 c-mr20" v-for="(item,index) in uploadAudioList" :key="index">
          <div @click="clickDelAudio(index)" class="del-icon">
            <i class="iconfont">&#xe8fd;</i>
          </div>
          <img class="c-ww30 c-hh30 c-rotate180" v-if="playAduioSrc != item.url" src="../../../assets/i/wap/course/chat_right_play.png" alt="" />
          <img class="c-ww30 c-hh30 c-rotate180" v-else src="../../../assets/i/wap/course/chat_right_play.gif" alt="" />
          <div class="c-fs20 c-fc-white">{{item.time}}"</div>
        </div> -->
      <div class="c-flex-row c-flexw-wrap" v-if="uploadAudioList.length > 0">
        <div @click.stop="clickPlayAudio(item.url)" v-for="(item,index) in uploadAudioList" :key="index" class="c-ww160 c-hh60 c-br30 theme-bg-10 c-pl24 c-pr10 c-p c-flex-row c-aligni-center c-mb30 c-mh10">
          <div class="box c-ww32">
            <div class="wifi-symbol">
              <div class="wifi-circle first theme-bd2"></div>
              <div class="wifi-circle second theme-bd2" :class="playAduioSrc == item.url?'seconAnimation':''"></div>
              <div class="wifi-circle third theme-bd2" :class="playAduioSrc == item.url?'thirdAnimation':''"></div>
            </div>
          </div>
          <div class="c-fs20 theme-fc">{{changeTimeStr(item.time)}}</div>
          <i @click.stop="clickDelAudio(index)" class="iconfont c-fs28 c-fc-gray del-img">&#xe6ec;</i>
        </div>
      </div>
      <div v-if="uploadAudioList.length > 0" class="c-fs20 c-fc-red c-ph20 c-mb30">录音总时长{{totalTime(uploadAudioList)}}</div>
      <!-- 视频回答 -->
      <!-- <div @click="clickShowVideo(item.realUrl || item.videoMp4)" class="c-p c-ww176 c-hh100 c-mb20 c-mr20" v-for="(item,index) in uploadVideoList" :key="index">
          <img class="c-w100 c-h" src="https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/clockIn/video-bg1.png" alt="" />
          <div @click="clickDelVideo(index)" class="del-icon">
            <i class="iconfont">&#xe8fd;</i>
          </div>
        </div> -->
      <div class="c-flex-row c-flexw-wrap" v-if="uploadVideoList.length > 0">
        <div v-for="(item,index) in uploadVideoList" :key="index">
          <div @click.stop="clickShowVideo(item.realUrl || item.videoMp4)" class="c-p c-ww160 c-hh100 c-mb30 c-mh10" :class="index % 3 == 0 ? '':'c-ml12'">
            <img class="c-w100 c-h c-br20" src="https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/clockIn/video-bg1.png" alt="" />
            <i @click.stop="clickDelVideo(index)" class="iconfont c-fs28 c-fc-gray del-img">&#xe6ec;</i>
          </div>
        </div>
      </div>
      <!-- 图片回答 -->
      <!-- <div v-for="(item,index) in uploadImgList" :key="index" class="c-ww100 c-hh100 c-mb20 c-p c-mr20">
          <div @click="delUploadImage(index)" class="del-icon">
            <i class="iconfont">&#xe8fd;</i>
          </div>
          <img @click="clickPreviewImage(item.url)" class="c-w100 c-h c-br4" :src="$addXossFilter(item.url)" alt="" />
        </div> -->
      <div class="c-flexw-wrap c-flex-row" v-if="uploadImgList.length > 0">
        <div v-for="(item,index) in uploadImgList" :key="index" class="c-ww160 c-hh160 c-mb30 c-mh10 c-flex-row c-flex-center c-p " :class="index % 3 == 0 ? '':'c-ml12'">
          <div @click="delUploadImage(index)" class="iconfont c-fs28 c-fc-gray del-img">&#xe6ec;</div>
          <img @click="clickPreviewImage(item.content)" class="c-ww160 c-hh160 c-br20" :src="$addXossFilter(item.url)" alt="" />
        </div>
      </div>
      <!-- 文档回答 -->
      <div v-if="uploadOfficeList.length > 0">
        <div @click="clickPrevireOffice(index)" v-for="(item,index) in uploadOfficeList" :key="index" class="c-p c-pv20 c-ph20 c-mb20 c-bg-F6F7F9 c-br20">
          <!-- <div @click="delUploadOffice(index)" class="del-icon">
            <i class="iconfont">&#xe8fd;</i>
          </div> -->
          <div @click="delUploadOffice(index)" class="iconfont c-fs28 c-fc-gray del-img">&#xe6ec;</div>
          <div class="c-flex-row c-aligni-center">
            <div>
              <img class="c-ww64 c-hh64 c-br20" :src="$addXossFilter(officeIconImg[item.type])" alt="" />
            </div>
            <div class="c-fs24 c-fc-xblack c-text-ellipsis2 c-ml16 c-ww410">
              {{item.name}}
            </div>
          </div>
        </div>
      </div>
      <!-- </div> -->
      <!-- 监护人电话 -->
      <div v-if="baseSetting.isNeedTutor != -1" class="c-flex-row c-aligni-center c-bd-b1-f5 c-pb24 c-pt10">
        <span v-if="baseSetting.isNeedTutor" class="c-fc-red c-fs20">*</span>
        <span class="c-pr24 c-fs20 c-fc-xblack" @click="showTip">监护人电话 <span class="icon-tishi1 iconfont c-fs20 c-fc-sgray c-ml12"></span></span>
        <input @focus="inputFocus" @blur="inputBlur" type="tel" v-model="tutorPhone" class="needsclick c-w0 c-fs24 c-flex-grow1 c-hh64 c-ph24 input-reset">
      </div>
      <!-- 选择回答类型 -->
      <div class="c-flex-row c-justify-sb c-pv10 c-pt20">
        <div class="c-flex-row c-fc-sblack">
          <div @click="clickAddAudio" class="c-mr60">
            <i class="iconfont c-fs32">&#xe75b;</i>
          </div>
          <div @click="clickUploadVideo" class="needsclick c-mr60">
            <i class="needsclick iconfont c-fs32">&#xe75d;</i>
          </div>
          <div class="c-p c-mr60">
            <div @click="clickAnswerPic" class="c-w100">
              <i class="iconfont c-fs32">&#xe75e;</i>
            </div>
          </div>
          <div @click="clickShowChooseOffice" class="needsclick">
            <i class="needsclick iconfont c-fs32">&#xe75c;</i>
          </div>
        </div>
        <div @click="clickSubmit" class="submit-bg theme-bg">提交</div>
      </div>
    </div>
    <div v-if="isDisCheat==2" class="c-mh24 c-bg-white c-flex-row c-justify-sb c-ph24 c-pv10 c-mt24 c-aligni-center c-br20">
      <div class="c-fs20 c-fc-xblack">打卡可见范围</div>
      <div class="c-fs20 c-fc-gray c-flex-row ">
        <div class="c-bd1-mgray c-pv6 c-ph18 c-mr20 c-br24 c-fw600" :class="enableShow==1?'theme-bd1 theme-bg-10 theme-fc':''" @click="enableShowAll">所有人</div>
        <div class="c-bd1-mgray c-pv6 c-ph18 c-br24 c-fw600" :class="enableShow==0?'theme-bd1 theme-bg-10 theme-fc':''" @click="enableShowOne">仅老师</div>
      </div>
    </div>
    <div class="c-pr24 c-fs20 c-ph20 c-pv20 c-mt10 c-fc-gray">
      <p class="c-mb6">1、视频文件过大时压缩时间较长，请耐心等待</p>
      <p class="c-mb6">2、建议您调整手机拍摄清晰度选择720p及以下的规格进行拍摄</p>
      <p class="c-mb6">3、若出现黑屏，请清理手机内存</p>
    </div>

    <clock-audio-record :isSimpleQue="true" :enableLongAudio='enableLongAudio' :isclock="true" :clockInInfo="homeWorkInfo" :showAudioRecordModal='showAudioRecordModal' @closeAudioRecordModal='closeAudioRecordModal' @uploadAudioSuccess='uploadAudioSuccess'></clock-audio-record>

    <input class="hide c-cursor-p needsclick" id="myUpload" type="file" accept="video/*" @change='onInputChange($event)' />
    <input class="hide c-cursor-p needsclick" id="myOfficeUpload" type="file" accept="*" @change='onInputOfficeChange' />

    <!-- 视频播放器 -->
    <video-popup :showVideo="showVideo" @clickCloseVideo="clickCloseVideo" :videoSrc="currentVideoObj.videoSrc" :m3u8Url="currentVideoObj.m3u8Url"></video-popup>
    <my-loading :showLoading="showProgress" :text="uploadProgress"></my-loading>
    <cj-actionsheet v-model="showChooseOffice" :item-list="officeMenu" show-cancel @choose='clickUploadOffice'></cj-actionsheet>
  </div>
</template>

<script>
import TcVod from "vod-js-sdk-v6";
import ClockCourseDetailCom from "@/components/templates/clockIn/clockCourseDetailCom.vue";
import clockAudioRecord from "@/components/templates/clockIn/clockAudioRecord.vue";
import videoPopup from "@/components/templates/common/videoPopup.vue";
import myLoading from "@/plugin/loading/loading.vue";
import { utilJs, wxUtilJs } from "@/utils/common.js";
import { ckjrRequest } from "@/utils/http.js";
const OFFICE_TYPE = {
  "application/msword": "doc",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
    "docx",
  "application/vnd.ms-excel": "xls",
  "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
  "application/vnd.ms-powerpoint": "ppt",
  "application/vnd.openxmlformats-officedocument.presentationml.presentation":
    "pptx",
  "application/pdf": "pdf",
  "text/plain": "txt"
};
const OFFICE_IMG_MAP = {
  doc: require("../../../assets/i/wap/clockIn/icon_word.png"),
  docx: require("../../../assets/i/wap/clockIn/icon_word.png"),
  xls: require("../../../assets/i/wap/clockIn/icon_excel.png"),
  xlsx: require("../../../assets/i/wap/clockIn/icon_excel.png"),
  ppt: require("../../../assets/i/wap/clockIn/icon_ppt.png"),
  pptx: require("../../../assets/i/wap/clockIn/icon_ppt.png"),
  pdf: require("../../../assets/i/wap/clockIn/icon_pdf.png"),
  txt: require("../../../assets/i/wap/clockIn/icon_txt.png")
};
let isLoading = false;
let curHwId = ""; //当前作业ID
let clockInId = ""; //当前课程ID
let examMainId = ""; //当前考试ID
let serverIdImgArr = []; //上传图片的serverID
let inputScrollTop = 0;
let uploader = null;
export default {
  name: "SimpleQue",
  components: {
    myLoading,
    ClockCourseDetailCom,
    clockAudioRecord,
    videoPopup,
  },
  props: [],
  beforeRouteLeave(to, from, next) {
    //当有评论弹窗的时候，后退就关闭弹窗,因为后退会把history历史栈后退一个，所以要添加回去
    if (this.showVideo) {
      this.showVideo = false;
      history.pushState(
        null,
        null,
        `${window.location.href.split("#")[0]}#${from.fullPath}`
      );
    } else {
      next();
    }
  },
  data() {
    return {
      userHeadImg: localStorage.getItem("userHeadImg"),
      officeIconImg: OFFICE_IMG_MAP,
      showChooseOffice: false,
      cfg: JSON.parse(localStorage.getItem("cfg")),
      officeMenu: [
        {
          name:'请选择文件',
          subTit:'（下载wps软件更快查找文档，支持word、ppt、excle、pdf、txt格式）</span>'
        }
      ],
      theme: localStorage.getItem("colorName")
        ? localStorage.getItem("colorName")
        : "mb5_default",
      showDesc: false, //显示课程
      showVideo: false, //显示视频
      showProgress: false,
      uploadProgress: '0',
      tutorPhone: "", //监护人电话
      answerText: "", //回答的文本内容
      playAduioSrc: "", //播放音频的src
      recordStatus: "START", //录音状态
      recordTime: 0, //录音时间
      isPlayTest: false, //是否试听播放
      showAudioRecordModal: false, //显示录音控制器
      uploadImgList: [], //需要上传的图片
      uploadAudioList: [], //需要上传的音频
      uploadVideoList: [], //需要上传的视频
      uploadOfficeList: [], //需要上传的文档
      homeWorkInfo: {},
      baseSetting: {},
      curSelectDate: "", //当前日历打卡日期
      ttId: "", //营期ID
      tpId: "", //环节ID
      tlId: "", //课时ID
      isWeiXin: true,
      isTraining:"",
      workTyp:'',
      currentVideoObj: {},
      answerPopupShow: false,
      enableShow:1,
      isDisCheat:0,
      enableLongAudio:0
    };
  },
  created() {
    utilJs.appShare(this);
  },
  computed: {

  },
  watch: {
    showAudioRecordModal(val) {
      if (val) {
        if (document.getElementById("audio")) {
          document.getElementById("audio").src = "";
        }
      }
    },
  },
  methods: {
    enableShowAll() {
      this.enableShow = 1
    },
    enableShowOne() {
      this.enableShow = 0
    },
    getBaseConfig() {
      let postUrl = `${global.apiurl}signCard/getBaseConfig?signColId=${clockInId}`;
      utilJs.getMethod(postUrl, (res) => {
        this.isDisCheat = res.isDisCheat
        this.enableLongAudio = res.enableLongAudio
      });
    },
    //时间转换成"形式
    changeTimeStr(timeStr) {
      return utilJs.timeTmpToNsTime(timeStr)
    },
    totalTime(uploadAudioList) {
      let totalTime = 0
      for (let item in uploadAudioList) {
        totalTime = totalTime + uploadAudioList[item].time
      }
      console.log(totalTime, '77777')
      return utilJs.timeTmpToStrTime(totalTime)
    },
    //IOS微信6.7以上版本会导致输入法收起的时候，键盘没收起，需要手动滚下屏幕
    inputFocus() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        inputScrollTop =
          document.documentElement.scrollTop || document.body.scrollTop;
      }
    },
    inputBlur() {
      if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        setTimeout(() => {
          document.body.scrollTop = inputScrollTop - 1 || 0;
        });
      }
    },
    clickPrevireOffice(index) {
      if (this.showAudioRecordModal) {
        return
      }
      let curType = this.uploadOfficeList.type;
      let curUrl = this.uploadOfficeList.url;
      switch (curType) {
        case "doc":
        case "docx":
        case "xls":
        case "xlsx":
        case "ppt":
        case "pptx":
          window.location.href = `https://view.officeapps.live.com/op/view.aspx?src=${curUrl}`;
          break;
        case "pdf":
        case "txt":
          window.location.href = curUrl;
          break;
      }
    },
    delUploadOffice(index) {
      this.uploadOfficeList.splice(index, 1);
    },
    clickShowChooseOffice() {
      if (this.showAudioRecordModal) {
        return
      }
      if (!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        this.$showCjToast({
          text:
            "pc端登入网页版微信---找到公众号打卡课程---点击按钮从本地上传文件",
          type: "warn",
          time: 1500
        });
      } else {
        this.showChooseOffice = true;
      }
    },
    //添加音频
    clickAddAudio() {
      if (this.showAudioRecordModal) {
        return
      }
      this.playAduioSrc = "";
      document.getElementById("audio").src = this.playAduioSrc;
      if (utilJs.getAppVersion() > 0) {
        this.initAppRecordEvent();
        utilJs.sendDataToAppNew('record', 'appAudioStartRecord');
        return;
      }
      this.showAudioRecordModal = true;
    },
    //关闭录音弹窗
    closeAudioRecordModal(state) {
      if (state == 1) {
        this.showAudioRecordModal = false;
      }
    },
    //音频上传成功
    uploadAudioSuccess(audioContent, state) {
      if (state == 1) {
        this.showAudioRecordModal = false;
      }
      let audioItem = {
        url: audioContent.content,
        time: audioContent.time
      };
      this.uploadAudioList.push(audioItem);
    },
    initAppRecordEvent() {
      window['cjAppAudioRecordResult'] = this.appRecordResult;
    },
    //app录音结果回调
    appRecordResult(resKey, time) {
      console.log('*******appRecordResult***', resKey, time)
      let resUrl = `https://qnoss.ckjr001.com/${resKey}`;
      let info = {
        content: resUrl,
        time:time
      }
      this.uploadAudioSuccess(info);
    },
    clickShowDesc(isShow) {
      this.showDesc = isShow;
    },

    //点击显示视频
    clickShowVideo(videoSrc, m3u8Url) {
      if (this.showAudioRecordModal) {
        return
      }
      this.showVideo = true;
      this.currentVideoObj = {videoSrc, m3u8Url}
    },
    //点击关闭视频
    clickCloseVideo() {
      if (this.showVideo) {
        this.showVideo = false;
      }
    },

    //点击开始播放音频
    clickPlayAudio(audioUrl) {
      if (this.showAudioRecordModal) {
        return
      }
      let audio = document.getElementById("audio");
      if (this.playAduioSrc == audioUrl) {
        this.playAduioSrc = "";
        document.getElementById("audio").src = this.playAduioSrc;
        return;
      }
      this.playAduioSrc = audioUrl;

      if (this.playAduioSrc && this.playAduioSrc.includes("http")) {
        document.getElementById("audio").src = this.playAduioSrc;
        audio.play();
      }
    },

    //监听音频播放结束执行的内容
    playAudioEnd() {
      this.playAduioSrc = "";
      document.getElementById("audio").src = this.playAduioSrc;
    },

    // 删除音频
    clickDelAudio(index) {
      if (document.getElementById("audio")) {
        this.playAduioSrc = "";
        document.getElementById("audio").src = this.playAduioSrc;
        document.getElementById("audio").pause();
      }
      this.uploadAudioList.splice(index, 1);
    },

    //点击回答图片
    async clickAnswerPic() {
      if (this.showAudioRecordModal) {
        return
      }
      if (this.uploadImgList.length >= 9) {
        this.$showCjToast({
          text: "图片最多只能传9张",
          type: "warn",
          time: 1500
        });
        return;
      }
      const isCloseWxUploadImg = localStorage.getItem("MP_IS_CLOSE_WX_UPLOAD_IMG");
      //在微信环境 && 开启了微信原生上传图片
      if (this.isWeiXin && isCloseWxUploadImg != 1) {
        wxUtilJs
          .chooseImage({
            count: 9, // 默认9
            sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ["album", "camera"] // 可以指定来源是相册还是相机，默认二者都有
          })
          .then((localIds) => {
            this.$loading.show({
              text: "上传中..."
            });
            serverIdImgArr = [];
            //获取剩余能传多少张图片，若已选的图片数量大于剩余数。则只传剩余数量的图片
            let residueLength = 9 - this.uploadImgList.length;
            if (localIds.length > residueLength) {
              localIds.length = residueLength;
            }
            this.wxUploadImg(localIds, localIds.length - 1);
          });
          return;
      }
      // 使用原生h5上传图片
      const fileList = await utilJs.chooseLocalFile({multiple:true, max:9});
      const imgList = await utilJs.uploadImgListToOss(fileList, {moduleName:'clock'});
      for (let item of imgList) {
        this.uploadImgList.push({
          url:item,
        })
      }
    },

    //上传图片到微信-----IOS不能一次性传多张，只好递归传
    wxUploadImg(localIds, localIdsLength) {
      wxUtilJs
        .uploadImage(
        {
          localId: localIds[localIdsLength]
        },
          true
        )
        .then((res) => {
          serverIdImgArr.push(res);
          if (localIdsLength > 0) {
            this.wxUploadImg(localIds, --localIdsLength);
          } else {
            this.syncUploadPic(serverIdImgArr);
          }
        });
    },

    //上传图片到服务器
    syncUploadPic(serverIdArr) {
      utilJs.postMethod(
        global.apiurl + "signCard/downWxImg ",
        {
          serverId: JSON.stringify(serverIdArr),
          mediaType: 2
        },
        (res) => {
          this.$loading.hide();
          for (let key of res) {
            if (this.uploadImgList.length >= 9) {
              break;
            }
            let urlObj = {
              url: key
            };
            this.uploadImgList.push(urlObj);
          }
        },
        (failRes) => {
          this.$loading.hide();
        }
      );
    },
    //删除上传的图片
    delUploadImage(index) {
      this.uploadImgList.splice(index, 1);
    },

    //点击图片放大预览
    clickPreviewImage(imgUrl) {
      if (this.showAudioRecordModal) {
        return
      }
      if (!imgUrl) {
        return;
      }
      let imgArr = [];
      for (let key of this.uploadImgList) {
        imgArr.push(key.url);
      }
      let imgData = {
        current: imgUrl, // 当前显示图片的http链接
        urls: imgArr
      }
      wxUtilJs.previewImage(imgData)
      // wxUtilJs.previewImage({
      //   current: imgUrl, // 当前显示图片的http链接
      //   urls: imgArr // 需要预览的图片http链接列表
      // });
    },

    // 删除视频
    clickDelVideo(index) {
      this.uploadVideoList.splice(index, 1);
    },

    //点击上传视频
    clickUploadVideo() {
      if (this.showAudioRecordModal) {
        return
      }
      if (this.uploadVideoList.length >= 9) {
        this.$showCjToast({
          text: "视频最多为9个",
          type: "warn",
          time: 1000
        });
        return
      }
      document.getElementById("myUpload").click();
    },
    //点击上传文档
    clickUploadOffice() {
      document.getElementById("myOfficeUpload").click();
    },
    //获取得到的文件file
    onInputChange(e) {
      let inputFile = e.target.files[0];
      if (inputFile && inputFile.size > 1024 * 1024 * 1024) {
        this.$showCjToast({
          text: "视频文件大小不能超过1G",
          type: "warn",
          time: 1000
        });
        return false;
      }
      if (inputFile) {
        this.uploadVideoToTencent(inputFile);
      }
    },
    uploadVideoToTencent(inputFile) {
      let that = this;
      this.showProgress = true;
      const tcVod = new TcVod({
        // eslint-disable-line
        getSignature: utilJs.getVideoSign
      });
      uploader = tcVod.upload({
        mediaFile: inputFile // 媒体文件（视频或音频或图片），类型为 File
      });
      uploader.on("media_progress", function (info) {
        that.uploadProgress = `上传进度:${Math.floor(info.percent * 100)}%`;
      });
      uploader
        .done()
        .then(function (result) {
          that.showProgress = false;
          let videoInfo = {
            url: result.fileId,
            realUrl: result.video.url
          };
          that.uploadVideoList.push(videoInfo);
          let data = {
            videoId: result.fileId,
            videoMp4: result.video.url,
            videoName: inputFile.name
          };
          that.videoFirstSave(data);
          that.uploadProgress = '0';
          document.getElementById("myUpload").value = null;
        })
        .catch((err) => {
          that.showProgress = false;
          that.$showCjToast({
            text: "上传失败，请尝试重新上传",
            type: "warn",
            time: 1000
          });
          that.uploadProgress = '0';
          document.getElementById("myUpload").value = null;
          let errorData = {
            errorMsg: JSON.stringify(err),
            errorType: "UPLOAD_VIDEO_ERROR"
          };
          utilJs.reprotError(errorData);
        });
    },
    // uploadVideoToTencent(inputFile) {
    //   let that = this;
    //   this.showProgress = true;
    //   qcVideo.ugcUploader.start({// eslint-disable-line
    //     videoFile: inputFile, //视频，类型为 File
    //     getSignature: this.getSignature, //前文中所述的获取上传签名的函数
    //     error: function (result) { //上传失败时的回调函数
    //       //...
    //       console.log('上传失败的原因：' + result.msg);
    //       that.showProgress = false;
    //       that.$showCjToast({
    //         text: "上传失败，请尝试重新上传",
    //         type: "warn",
    //         time: 1000,
    //       });
    //       that.uploadProgress = 0;
    //       document.getElementById('myUpload').value = null;
    //       let errorData = {
    //         errorMsg: result && result.msg,
    //         errorType: 'UPLOAD_VIDEO_ERROR',
    //       }
    //       utilJs.reprotError(errorData)
    //     },
    //     progress: function (result) {
    //       if (result.shacurr == 1) {
    //         that.uploadProgress = `上传进度:${Math.floor(result.curr * 100)}%`
    //       } else {
    //         that.uploadProgress = `解析进度:${Math.floor(result.shacurr * 100)}%`
    //       }
    //     },
    //     finish: function (result) { //上传成功时的回调函数
    //       that.showProgress = false;
    //       let videoInfo = {
    //         url: result.fileId,
    //         realUrl: result.videoUrl
    //       };
    //       that.uploadVideoList.push(videoInfo);
    //       let data = {
    //         videoId: result.fileId,
    //         videoMp4: result.videoUrl,
    //         videoName: result.videoName,
    //       }
    //       that.videoFirstSave(data);
    //       that.uploadProgress = 0;
    //       document.getElementById('myUpload').value = null;
    //       console.log('上传结果的fileId：' + result.fileId);
    //       console.log('上传结果的视频名称：' + result.videoName);
    //       console.log('上传结果的视频地址：' + result.videoUrl);
    //     }
    //   });
    // },
    //获取得到的文档文件file
    onInputOfficeChange(e) {
      let inputFile = e.target.files[0];
      if (inputFile && inputFile.type && !OFFICE_TYPE[inputFile.type]) {
        this.$showCjToast({
          text: "文件类型错误，请上传正确的文件",
          type: "warn",
          time: 1000
        });
        return false;
      }
      if (inputFile) {
        this.showProgress = true;
        let postUrl = `${global.apiurl}common/signCard/uploadFile `;
        let formData = new FormData();
        formData.append("file", inputFile);
        this.postFormData(postUrl, formData)
          .then((res) => {
            let officeItem = {
              url: res.fileUrl,
              name: res.name,
              type: res.type
            };
            this.uploadOfficeList.push(officeItem);
            this.showProgress = false;
            this.uploadProgress = '0';
            document.getElementById("myOfficeUpload").value = null;
          })
          .catch((res) => {
            this.showProgress = false;
            this.uploadProgress = '0';
            document.getElementById("myOfficeUpload").value = null;
            this.$showCjToast({
              text: "上传失败，请尝试重新上传",
              type: "warn",
              time: 1000
            });
            let errorData = {
              errorMsg: JSON.stringify(res),
              errorType: "UPLOAD_OFFICE_ERROR"
            };
            utilJs.reprotError(errorData);
          });
      }
    },
    postFormData(url, formData) {
      let that = this;
      return new Promise((resolve, reject) => {
        ckjrRequest({
          url: url,
          method: "post",
          data: formData,
          headers: {
            "Content-Type": "multipart/form-data"
          },
          onUploadProgress: function (e) {
            let progress = e.loaded / e.total;
            if (progress == 1) {
              that.uploadProgress = `上传成功，解析中...`;
            } else {
              that.uploadProgress = `上传进度:${Math.floor(progress * 100)}%`;
            }
          }
        }).then((res) => {
          if (res.status == 200 && res.data.statusCode == 200) {
            resolve(res.data.data);
          } else {
            reject(res.data.msg || "系统错误");
          }
        });
      });
    },
    //保存视频
    videoFirstSave(data) {
      utilJs.postMethod(
        global.apiurl + "signCard/videoFirstSave",
        data,
        (res) => {}
      );
    },
    showTip() {
      let textMessage = '1、监护人电话不能填写打卡本人的电话<br/>2、监护人电话必须是进入过该公众号平台的手机号，如果填写的手机号提示：手机号填写有误，平台下未存在该用户，则需要用该手机号微信进入该公众号平台绑定后输入才有效。'
      this.$cjConfirm({
        title: '监护人电话要求', //
        titleCenter: true, //标题是否居中
        message: textMessage,
        messageCenter: false, //内容是否居中
        showMasker: true, //是否显示透明背景
        clickCloseModal: false, //是否点击透明背景关闭弹窗
        showCancelButton: false, //是否显示取消按钮
        cancelButtonText: '', //取消按钮文本
        confirmButtonText: '好的', //确认按钮文本
        color:'',
        onConfirm() {
        },
      })
    },
    //提交前校验
    checkSubmit() {
      let minTime = 60;
      for (let key of this.uploadAudioList) {
        if (key.time < minTime) {
          minTime = key.time;
        }
      }
      if (
        this.answerText == "" &&
        this.uploadImgList.length == 0 &&
        this.uploadAudioList.length == 0 &&
        this.uploadVideoList.length == 0
      ) {
        this.$showCjToast({
          text: "没有提交任何内容",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (this.baseSetting.isNeedTutor == 1 && this.tutorPhone == "") {
        this.$showCjToast({
          text: "请填写监护人手机号",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (
        this.baseSetting.isNeedTutor != -1 &&
        this.tutorPhone &&
        this.tutorPhone == localStorage.getItem("uMobile")
      ) {
        this.$showCjToast({
          text: "监护人手机号不能是自己的",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (this.answerText.length > 10000) {
        this.$showCjToast({
          text: "字数最多为10000字",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (this.answerText.length < this.baseSetting.needWordNum) {
        this.$showCjToast({
          text: "字数最少为" + this.baseSetting.needWordNum + "字",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (this.uploadImgList.length < this.baseSetting.needPictureNum) {
        this.$showCjToast({
          text: "图片最少为" + this.baseSetting.needPictureNum + "张",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (
        this.uploadAudioList.length == 0 &&
        this.baseSetting.needAudioNum * 1 > 0
      ) {
        this.$showCjToast({
          text: "音频最少为" + this.baseSetting.needAudioNum + "秒",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (
        this.uploadAudioList.length > 0 &&
        minTime < this.baseSetting.needAudioNum
      ) {
        this.$showCjToast({
          text: "音频最少为" + this.baseSetting.needAudioNum + "秒",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (this.uploadVideoList.length < this.baseSetting.needVideoNum) {
        this.$showCjToast({
          text: "视频最少为" + this.baseSetting.needVideoNum + "个",
          type: "warn",
          time: 1000
        });
        return false;
      } else if (this.uploadVideoList.length > 9) {
        this.$showCjToast({
          text: "视频最多为9个",
          type: "warn",
          time: 1000
        });
        return false;
      } else {
        return true;
      }
    },

    //确认提交
    clickSubmit() {
      if (this.showAudioRecordModal) {
        return
      }
      if (!this.checkSubmit()) {
        return;
      }
      if (isLoading) {
        return;
      }
      isLoading = true;
      let that = this;
      this.answerText = utilJs.checkScriptStr(this.answerText)
      let data = {
        day: this.curSelectDate,
        hwId: curHwId,
        signColId: this.homeWorkInfo.signColId,
        examMainId: examMainId,
        word: this.answerText,
        imgArr: this.uploadImgList,
        audioArr: this.uploadAudioList,
        videoArr: this.uploadVideoList,
        filesArr: this.uploadOfficeList,
        tutor: this.tutorPhone,
        enableShow: this.enableShow
      };
      let postUrl = this.curSelectDate
        ? `${global.apiurl}signCard/saveDayAnswer`
        : `${global.apiurl}signCard/saveAnswer/${curHwId}`;
      utilJs.postMethod(
        postUrl,
        data,
        (res) => {
          // isLoading = false;
          localStorage.setItem(`camp${this.tlId}`, 100);
          if (this.ckFrom == global.ckFrom.camp) {
            // 记录播放进度
            let data = {
              ttId: this.ttId, //营期ID
              tpId: this.tpId, //环节ID
              tlId: this.tlId, //课时ID
              ratio: 100 //完成进度0-100
            };
            utilJs.postMethod(
              global.apiurl + "k12/trainings/progress",
              data,
              function (res) {}
            );
          }
          this.$showCjToast({
            text: "提交成功",
            type: "success",
          }).then(() => {
            that.clickLookShortAnswerResult(res.examMainId)
          });
        },
        (failRes) => {
          isLoading = false;
        }
      );
    },
    //简答题答题长图页
    clickLookShortAnswerResult(examMainId) {
      this.$routerGo(this, "replace", {
          path: "/homePage/clockIn/shortAnswerResult",
          query: {
            clockInId: clockInId,
            curHwId : this.homeWorkInfo.hwId,
            curSelectDate:this.curSelectDate,
            ttId: this.ttId,
            tpId: this.tpId,
            tlId: this.tlId,
            ckFrom: this.ckFrom,
            isTraining:this.isTraining,
            workType:this.workType,
            examMainId:examMainId
          }
        });
    },
    //获取草稿的信息
    getHistoryDetail() {
      let postUrl = `${global.apiurl}signCard/readTemporaryStorage?signColId=${clockInId}&startDay=${this.curSelectDate}&hwId=${curHwId}`;
      utilJs.getMethod(postUrl, (res) => {
        this.baseSetting = res.baseSetting;
        if (res) {
          this.answerText = res.word;
          this.tutorPhone = res.tutor;
          this.uploadImgList = res.imgArr;
          this.uploadAudioList = res.audioArr;
          this.uploadVideoList = res.videoArr;
          this.uploadOfficeList = res.filesArr;
          this.enableShow = res.enableShow
        }
        this.tutorPhone = res.tutor
          ? res.tutor
          : this.tutorPhone;
      });
    },
    //获取编辑的信息
    getEidtDetail() {
      let postUrl = this.curSelectDate
        ? `${global.apiurl}signCard/dayAnswerInfo?day=${
            this.curSelectDate
          }&signColId=${clockInId}&examMainId=${examMainId}`
        : `${global.apiurl}signCard/shortAnswerInfo/${curHwId}`;
      utilJs.getMethod(postUrl, (res) => {
        this.baseSetting = res.baseSetting;
        if (res.examInfo) {
          this.answerText = res.examInfo.word;
          this.tutorPhone = res.examInfo.tutor;
          this.uploadImgList = res.examInfo.imgArr;
          this.uploadAudioList = res.examInfo.audioArr;
          this.uploadVideoList = res.examInfo.videoArr;
          this.uploadOfficeList = res.examInfo.filesArr;
          this.enableShow = res.examInfo.enableShow;
        }
        this.tutorPhone = res.baseSetting.hasSetPhone
          ? res.baseSetting.hasSetPhone
          : this.tutorPhone;
      });
    },

    //获取作业本信息
    getHomeWorkDatail() {
      utilJs.getMethod(
        global.apiurl + "signCard/homeworkDetail/" + curHwId,
        (res) => {
          this.homeWorkInfo = res;
        }
      );
    },

    //获取日历打卡信息
    getCalendarHomeWork() {
      utilJs.getMethod(
        `${global.apiurl}signCard/themeDetail?signColId=${clockInId}&day=${
          this.curSelectDate
        }`,
        (res) => {
          this.homeWorkInfo = {
            hwId: res.headInfo.hwId || 0,
            signColId: clockInId,
            name: res.headInfo.name || "",
            cover: res.headInfo.cover || "",
            description: res.headInfo.description || [],
          };
        }
      );
    },

    initData() {
      isLoading = false;
      serverIdImgArr = []; //上传图片的serverID
      this.ttId = this.$route.query.ttId || "";
      this.tpId = this.$route.query.tpId || "";
      this.tlId = this.$route.query.tlId || "";
      this.ckFrom = this.$route.query.ckFrom || "";
      this.isTraining = this.$route.query.isTraining || "";
      this.workType = this.$route.query.workType || "";
      examMainId = this.$route.query.examMainId || -1;
      this.showChooseOffice = false;
      this.showDesc = false;
      this.showVideo = false;
      this.showProgress = false;
      this.uploadProgress = '0';
      this.tutorPhone = "";
      this.answerText = "";
      this.playAduioSrc = "";
      this.recordStatus = "START";
      this.recordTime = 0;
      this.isPlayTest = false;
      this.showAudioRecordModal = false;
      this.uploadImgList = [];
      this.uploadAudioList = [];
      this.uploadVideoList = [];
      this.uploadOfficeList = [];
      this.homeWorkInfo = {};
      this.baseSetting = {};
      this.currentVideoObj = {};
    },

    //分享
    wechatShare: function () {
      let title = window.localStorage.getItem("companyName");
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareDesc = window.localStorage.getItem("shareDesc");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`
      let shareIndexData = {
        shareUrl,
        title,
        shareImg,
        shareDesc,
      };
      let shareData = localStorage.getItem("homeWorkShare") ? JSON.parse(localStorage.getItem("homeWorkShare")) : shareIndexData;
      utilJs.wechatConfig(
        shareData.shareUrl,
        shareData.title,
        shareData.shareImg,
        shareData.shareDesc,
        function () {},
        true
      );
    },
    //手机端分享
    appShare: function () {
      let title = window.localStorage.getItem("companyName");
      let shareImg = window.localStorage.getItem("shareLogo");
      let shareDesc = window.localStorage.getItem("shareDesc");
      let shareUrl = `${window.location.href.split("#")[0]}#${this.$route.path}?refereeId=${localStorage.getItem("userId")}`
      let shareIndexData = {
        shareUrl,
        title,
        shareImg,
        shareDesc,
      };
      let shareData = localStorage.getItem("homeWorkShare") ? JSON.parse(localStorage.getItem("homeWorkShare")) : shareIndexData;
      utilJs.appShareTrue(
        shareData.title,
        shareData.shareImg,
        shareData.shareUrl,
        shareData.shareDesc
      );
    },
    temporaryStorage() {
      if (isLoading || examMainId != 0) {
        return
      }
      let data = {
          startDay: this.curSelectDate,
          hwId: curHwId,
          signColId: this.homeWorkInfo.signColId,
          examMainId: examMainId,
          word: this.answerText,
          imgArr: JSON.stringify(this.uploadImgList),
          audioArr: JSON.stringify(this.uploadAudioList),
          videoArr: JSON.stringify(this.uploadVideoList),
          filesArr: JSON.stringify(this.uploadOfficeList),
          tutor: this.tutorPhone,
          isClose: 1,
          enableShow: this.enableShow,
          encodeCompanyId: localStorage.getItem("companyId") ? localStorage.getItem("companyId") : '',
          encodeUserId: localStorage.getItem("userId") ? localStorage.getItem("userId") : ''
        }
      let postUrl = `${global.apiurl}signCard/temporaryStorage`;
      utilJs.berforeCloseSendData(postUrl, data);
    },
  },
  activated() {
    setDocumentTitle("发表日记"); // eslint-disable-line
    if (document.getElementById("audio")) {
      document.getElementById("audio").src = "";
    }
    this.isWeiXin = utilJs.isWeiXin() && utilJs.isMobileUserAgent();
    this.initData();
    curHwId = this.$route.query.curHwId;
    clockInId = this.$route.query.clockId || "";
    this.curSelectDate = this.$route.query.curDate || "";
    examMainId = this.$route.query.examMainId || 0;
    uploader = null;
    if (document.getElementById("myUpload")) {
      document.getElementById("myUpload").value = null;
    }
    if (examMainId == 0) {
      this.getHistoryDetail()
    } else {
      this.getEidtDetail();
    }
    if (this.curSelectDate) {
      this.getCalendarHomeWork();
    } else {
      this.getHomeWorkDatail();
    }
    this.getBaseConfig()
    window.removeEventListener("unload", this.temporaryStorage, false);
    window.addEventListener("unload", this.temporaryStorage, false);
    this.wechatShare();
    //解决ios播放没声音
    try {
      document.addEventListener(
        "WeixinJSBridgeReady",
        function () {
          document.getElementById("audio").play();
        },
        false
      );
      WeixinJSBridge.invoke("getNetworkType", {}, function (e) {
        // eslint-disable-line
        // 在这里拿到 e.err_msg, 这里面就包含了所有的网络类型
        document.getElementById("audio").play();
        console.log("WeixinJSBridgeWeixinJSBridgeWeixinJSBridgeWeixinJSBridge");
      });
    } catch (error) {
      // continue regardless of error
    }
  },
  deactivated() {
    if (document.getElementById("audio")) {
      document.getElementById("audio").src = "";
    }
    this.temporaryStorage()
    window.removeEventListener("unload", this.temporaryStorage, false);
    uploader && uploader.cancel();
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>
.submit-bg {
  color: #fff;
  font-size: .55rem;
  border-radius: .8rem;
  text-align: center;
  height: 1.2rem;
  line-height: 1.2rem;
  padding: 0 1rem;
  /* background-image: linear-gradient(90deg, #FE9901 0%, #FEB74C 100%); */
}
.input-reset {
  border: 1px solid #e5e5e5!important;
}
.modal {
  z-index: 40003!important;
}
/deep/ .weui-mask {
  z-index: 40003!important;
}
/deep/ .weui-actionsheet {
  z-index: 50003!important;
}
.modal-textarea {
  padding: 0.75rem 0 0.5rem 0rem;
  width: 100%;
  height: 6.9rem;
  display: flex;
  flex-direction: column;
  background-color: #F6F7F9;
  /* border-radius: .25rem; */
  padding-left: .5rem;
  padding-right: .5rem;
}

.modal-textarea textarea {
  font-size: 0.6rem;
  outline: none;
  border: none;
  width: 100%;
  height: 100%;
  background: none;
  -webkit-appearance: none;
  resize: none;
}

.modal-textarea textarea:focus {
  outline: none;
}
.del-img {
  position: absolute;
  top: 0rem;
  right: 0rem;
  /* cursor: pointer;
  background: rgba(0, 0, 0, 0.3); */
}
.del-icon  {
  position: absolute;
  top: -0.3rem;
  right: -0.3rem;
  width: .6rem;
  height: .6rem;
  border-radius: 50%;
  background: #FF4040;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}
.del-icon .iconfont{
  transform: scale(0.3);
  font-size: .8rem;
  display: block;
  font-weight: bold;
}

.box-bl-r8 {
  border-bottom-left-radius: 0.2rem;
  border-bottom-right-radius: 0.2rem;
}
.vux-popup-dialog {
  background-color: #fff;
  border-radius: 10px 10px 0 0;
}
.box {
  box-sizing: border-box;
  position: relative;
}
.wifi-symbol {
  width: 1rem;
  height: 1rem;
  overflow: hidden;
  position: relative;
  transform: rotate(135deg);
  -webkit-transform-origin: center;
  transform-origin: center;
  -webkit-transform: translate3d(135deg,0,0);
  -webkit-backface-visibility: hidden;
}
.wifi-circle {
  /* border: 0.1rem solid #999999; */
  border-radius: 50%;
  overflow: hidden;
  -webkit-backface-visibility: hidden;
  position: absolute;
  -webkit-transform: translate3d(0,0,0);
}

.first {
  width: 0.1rem;
  height: 0.1rem;
  background: #cccccc;
  top: 0.9rem;
  left: 0.9rem;
}
.second {
  width: 0.5rem;
  height: 0.5rem;
  top: 0.7rem;
  left: 0.7rem;
}
.seconAnimation{
  animation: fadeInOut 1s infinite 0.2s;
}
.third {
  width: 0.8rem;
  height: 0.8rem;
  top: 0.5rem;
  left: 0.5rem;
}
.thirdAnimation{
  animation: fadeInOut 1s infinite 0.4s;
}
@keyframes fadeInOut {
    0% {
        opacity: 0; /*初始状态 透明度为0*/
    }
    100% {
        opacity: 1; /*结尾状态 透明度为1*/
    }
}
</style>
